package com.augurit.gzcgwsp.sendNotice.foresee.gzcgw.webservice.util;

import sun.misc.BASE64Decoder;

import com.foresee.spiderweb.console.security.bean.ServiceResult;
import com.foresee.synectic.webservice.client.Client;
import com.foresee.synectic.webservice.client.ClientFactory;
import com.foresee.synectic.webservice.client.tools.ResponseStatus;

/**
 * 服务调用工具类
 * @version 1.0 2011-02-11
 * @author 郭子瑜
 */
public class WSInvoker {
	
	/**
	 * 调用WebService服务
	 * @param wsdl
	 * @param serviceName
	 * @param operation
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public ServiceResult invokeWS(String wsdl,String serviceName,String operation,Object[] params) throws Exception {
		return parseResultInfo(invoke(wsdl,serviceName,operation,params),operation);
	}
	
	/**
	 * 调用WebService服务
	 * @param wsdl
	 * @param serviceName
	 * @param operation
	 * @param params
	 * @return
	 * @throws Exception
	 */
	private Object invoke(String wsdl,String serviceName,String operation,Object[] params) throws Exception {
		
		Client client = ClientFactory.newInstance();
		return client.invokeValidate(wsdl, serviceName, operation, params,"admin","admin");
	}
	
	/**
	 * 解析调用结果
	 * @param result
	 * @param method
	 * @return
	 * @throws Exception
	 */
	private ServiceResult parseResultInfo(Object result,String method) throws Exception {
		if(result == null || "".equals(result)) {
			return null;
		}
		BASE64Decoder decoder = new BASE64Decoder();
		ServiceResult serviceResult = new ServiceResult();;
		try {						
			result = parseReturn(result.toString(),method);
			String tt = new String(decoder.decodeBuffer(result.toString()), "UTF-8");
			int frist = tt.indexOf("<result>");
			int second = tt.lastIndexOf("result>");
			String resultMsg = tt.substring(frist+"<result>".length(), second - 2);
			ResponseStatus status = new ResponseStatus(resultMsg);
			String retCode = status.getRetCode();
			String retMessage = status.getRetMessage();
			serviceResult.setRetCode(retCode);
			serviceResult.setRetMessage(retMessage);
		} catch (Exception e) {
			throw new Exception("解析返回结果出错:" + e.getMessage());
		}				
		return serviceResult;		
	}
	
	/**
	 * 解析调用结果
	 * @param origin
	 * @param method
	 * @return
	 */
	private String parseReturn(String origin,String method) {
		String prefix = "<" + method + "Return>";
		int frist = origin.indexOf(prefix);
		int second = origin.lastIndexOf(method + "Return>");
		String returnMsg = origin.substring(frist+prefix.length(), second - 2);
		return returnMsg;
	}
}
